// src/stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed, reactive } from 'vue'
// import api from '@/auth/myaxios'
import tokenService from '@/auth/tokenManage'
const parseJwt = (token) => {
  try {
    const parts = token.split('.')
    if (parts.length !== 3) return null

    // 解码payload部分 (base64url -> string -> JSON)
    const decoded = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')))
    return decoded
  } catch (error) {
    console.error('解析Token失败:', error)
    return null
  }
}
export const useAuthStore = defineStore('auth', () => {
  const token = ref(tokenService.getAccessToken() || '')
  const user = reactive({ id: null, username: '', role: '', name: '', email: '' })
  const isAuthenticated = computed(() => !!token.value && user.id !== null)
  const isInitialized = ref(false) // 新增：标记是否已初始化

  // 初始化用户状态
  const initUser = async () => {
    if (isInitialized.value) return true

    const storedToken = tokenService.getAccessToken()
    if (!storedToken) return false

    try {
      // 直接解析Token获取用户信息
      const payload = parseJwt(storedToken)
      if (!payload || !payload.user_id) {
        throw new Error('无效的Token格式')
      }

      // 填充用户信息（从Token解析）
      user.id = payload.user_id
      user.username = payload.username || ''
      user.role = payload.role || ''
      user.name = payload.name || ''
      user.email = payload.email || ''
      token.value = storedToken
      isInitialized.value = true
      return true
    } catch (error) {
      console.error('初始化用户失败:', error)
      logout()
      tokenService.handleAuthFailure()
      return false
    }
  }
  // 登出
  const logout = () => {
    token.value = ''
    user.id = null
    user.username = ''
    user.role = ''
    tokenService.clearTokens()
  }

  return {
    token,
    user,
    role: computed(() => user.role),
    isAuthenticated,
    initUser,
    isInitialized,
  }
})
